package com.neihe.listenner;


import cn.hutool.core.collection.CollUtil;
import com.neihe.common.enums.DelFlagEnum;
import com.neihe.entity.UserFile;
import com.neihe.listenner.event.RecycleFileEvent;
import com.neihe.listenner.event.RestoreFileEvent;
import com.neihe.service.IShareService;
import com.neihe.service.IUserFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 监听文件状态变更导致分享状态变更的处理器
 */
@Slf4j
@Component
public class ShareStatusChangeListener {

    @Autowired
    private IUserFileService userFileService;

    @Autowired
    private IShareService shareService;

    /**
     * 监听文件被放入回收站事件
     */
    @EventListener(RecycleFileEvent.class)
    public void changeShare2FileDeleted(RecycleFileEvent event) {
        List<Long> fileIds = event.getFileIds();
        if (CollUtil.isEmpty(fileIds)) {
            return;
        }
        List<UserFile> allRecords = userFileService.findAllFileRecordsByFileIdList(fileIds);
        List<Long> allAvailableFileIdList = allRecords.stream()
                .filter(record -> Objects.equals(record.getDelFlag(), DelFlagEnum.NO.getCode()))
                .map(UserFile::getFileId)
                .collect(Collectors.toList());
        allAvailableFileIdList.addAll(fileIds);
        shareService.refreshShareStatus(allAvailableFileIdList);
    }

    /**
     * 监听文件被还原事件
     */
    @EventListener(RestoreFileEvent.class)
    public void changeShare2Normal(RestoreFileEvent event) {
        List<Long> fileIds = event.getFileIds();
        if (CollUtil.isEmpty(fileIds)) {
            return;
        }
        List<UserFile> allRecords = userFileService.findAllFileRecordsByFileIdList(fileIds);
        List<Long> allAvailableFileIdList = allRecords.stream()
                .filter(record -> Objects.equals(record.getDelFlag(), DelFlagEnum.NO.getCode()))
                .map(UserFile::getFileId)
                .collect(Collectors.toList());
        allAvailableFileIdList.addAll(fileIds);
        shareService.refreshShareStatus(allAvailableFileIdList);
    }

}
